#include "lib.c"

int main (int argc, char *argv[]) {
	enum keys key;
	int rkey;
	int x = SXDIV2,
		y = SYDIV2;
	int i, j;
	int counter = 0;
	
	InitBoard(&gboard);
	rk_mytermregime(0, 0, 0, 0, 1);	
	mt_clrscr();
	
	PrintBoard(gboard);
	mt_gotoXY(x, y);
	
	rkey = rk_readkey(&key);
	while (key != K_F5) {
		if ((i = IsEnd()) != 0) {
			printf("Player %d wins!", i);
			printf(" (%s)\n", i == 1 ? "CROSS" : "CRISS");
			break;
		}
		
		if (counter == FIELDSIZE * FIELDSIZE) {
			printf("Nobody wins.\n");
			break;
		}
		
		rkey = rk_readkey(&key);
		if (!rkey) {
			switch (key) {
			case K_DOWN:
				y = y <= FIELDSIZE * SYDIV2 ? y + (CELLSIZEY + 1) : SYDIV2;
				mt_gotoXY(x, y);
			break;
			case K_UP:
				y = y - SYDIV2 > 0 ? y - (CELLSIZEY + 1) : SYDIV2 + (FIELDSIZE - 1) * (CELLSIZEY + 1);
				mt_gotoXY(x, y);
			break;
			case K_LEFT:
				x = x - SXDIV2 > 0 ? x - (CELLSIZEX + 1) : SXDIV2 + (FIELDSIZE - 1) * (CELLSIZEX + 1);
				mt_gotoXY(x, y);
			break;
			case K_RIGHT:
				x = x <= FIELDSIZE * SXDIV2 ? x + (CELLSIZEX + 1) : SXDIV2;
				mt_gotoXY(x, y);
			break;
			case K_ENTER:
				i = (x - SXDIV2) / (CELLSIZEX + 1);
				j = (y - SYDIV2) / (CELLSIZEY + 1);
				
				if (gboard.cell[i][j] == NONE) {
					gboard.cell[i][j] = counter % 2 ? CRISS : CROSS;
					counter++;
				}
				PrintBoard(gboard);
				mt_gotoXY(x, y);
			break;
			default:
			break;
			}
		}
	}
	rk_mytermrestore();
	return 0;
}
